package cn.edu.ujs.coor.common.resolver;

import cn.edu.ujs.coor.model.User;
import cn.edu.ujs.coor.repository.role.RoleRepository;
import cn.edu.ujs.coor.util.JwtUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.util.Map;

@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private RoleRepository roleRepository;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType().equals(User.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        String token = nativeWebRequest.getHeader("token");
        Map<String, String> info = JwtUnit.decode(token);
        User user = User
                .builder()
                .id(info.get("id"))
                .name(info.get("name"))
                .phone(info.get("phone"))
                .email(info.get("email"))
                .organizationId(info.get("organizationId"))
                .dataLevel(info.get("dataLevel"))
                .build();
        return user;
    }
}